<template>
  <div style="width: 100%; height: 100%">
    <div class="video-play" :id="state.pid"></div>
    <div class="video-cover" v-if="showtab">
      <span class="btnv" @click="emitTalk">
        <img src="../../assets/images/l1.png" /> 远程驱离</span
      >
      <span class="btnv" @click="changeVideo"
        ><img src="../../assets/images/c2.png" />{{
          playStatus ? "录像回放" : "视频预览"
        }}</span
      >
      <span class="btnv">
        <img src="../../assets/images/r3.png" @click="zoom" />放大</span
      >
    </div>
  </div>
</template>

<script setup>
import SelfDialog from "@/components/dialog/dialog.vue";
import { ElMessage } from "element-plus";
import { getPointUrl, getPointUrlBack, talkToseppk } from "@/api/event.js";
import dayjs from "dayjs";
import { useUserStore } from "@/pinia/user.js";
const piniaUser = useUserStore();
const emit = defineEmits(["showql"]);
const props = defineProps({
  vid: String,
  Times: String,
  showtab: {
    type: Boolean,
    default: true,
  },
});
const state = reactive({
  myPlugin: null,
  curIndex: 0,
  pid: "one" + Math.floor(Math.random() * 1000) + 1,
  // zoom: false,
});

let playStatus = ref(true);

const changeVideo = () => {
  playStatus.value = !playStatus.value;
  if (playStatus.value) {
    play();
  } else {
    playBack();
  }
};

// 回放
const playBack = async () => {
  try {
    debugger;
    let bt = dayjs(new Date(props.Times))
      .subtract(10, "second")
      .format("YYYY-MM-DDTHH:mm:ss.SSSZ");
    let et = dayjs(new Date(props.Times))
      .add(10, "second")
      .format("YYYY-MM-DDTHH:mm:ss.SSSZ");
    let pm = {
      cameraId: props.vid,
      beginTime: bt,
      endTime: et,
      uuid: "",
    };
    let { data } = await getPointUrlBack({
      ...pm,
    });
    if (data.url) {
      state.myPlugin
        .JS_Play(data.url, { playURL: data.url, mode: 1 }, 0, bt, et)
        .then(
          () => {},
          (err) => {
            // play();
          }
        );
    }
    //根据选择 获取监控点播放地址，尝试播放
    // useApi.post("/arhome/camera/getplaybackurls", pm).then((res) => {
    //   let url = res.data.url || "";
    //   if (url != "") {
    //     // state.myPlugin.JS_StopRealPlayAll();
    //     state.myPlugin.JS_Play(url, { playURL: url, mode: 1 }, 0, bt, et).then(
    //       () => {},
    //       (err) => {
    //         play();
    //       }
    //     );
    //   } else {
    //     ElMessage.error("未获取到播放地址");
    //   }
    // });
  } catch (e) {
    console.error(e);
  }
};

const play = async () => {
  let ids = [props.vid];
  //根据选择 获取监控点播放地址，尝试播放
  let { data } = await getPointUrl({ deviceIds: ids });
  // let data = []
  let urls = data.cameraUrls || [];
  if (urls.length > 0) {
    state.myPlugin.JS_StopRealPlayAll();
    for (let i = 0; i < urls.length; i++) {
      if (i > 8) break;
      state.myPlugin
        .JS_Play(urls[i].cameraUrl, { playURL: urls[i].cameraUrl, mode: 1 }, i)
        .then(
          () => {
            resize();
          },
          (err) => {}
        );
    }
  }
};
const initPlayer = () => {
  if (state.myPlugin != null) return;
  state.myPlugin = new JSPlugin({
    szId: state.pid, //需要英文字母开头，唯一性，必填
    szBasePath: "/js/", // 必填,与h5player.min.js的引用目录一致
    bSupporDoubleClickFull: true, //是否支持双击全屏，默认true
    // 分屏播放，默认最大分屏4*4
    iMaxSplit: 1,
    iCurrentSplit: 1,
  });

  state.myPlugin.JS_SetWindowControlCallback({
    windowEventSelect: function (index) {
      //插件选中窗口回调
      state.curIndex = index;
    },
    pluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
      //插件错误回调
      console.error(`window-${iWndIndex}, errorCode: ${iErrorCode}`, oError);
      //ElMessage.error(`播放失败, 错误码: ${iErrorCode}`);
      play();
    },
    windowFullCcreenChange: function (bFull) {
      //全屏切换回调
      // setTimeout(() => {
      //   //state.myPlugin.JS_ArrangeWindow(1)
      //   state.myPlugin.JS_Resize()
      // }, 50);
    },
  });
};
const destoryPlayer = () => {
  if (state.myPlugin) {
    state.myPlugin.JS_StopRealPlayAll();
    state.myPlugin.JS_DestroyWorker();
    state.myPlugin = null;
  }
};
const resize = () => {
  if (state.myPlugin) {
    setTimeout(() => {
      state.myPlugin.JS_Resize();
    }, 50);
  }
};

// 缩放
const zoom = () => {
  if (state.zoom == false) {
    state.zoom = true;
    state.myPlugin.JS_EnableZoom(state.curIndex).then(
      () => {
        console.info("JS_EnableZoom success");
      },
      (err) => {
        console.info("JS_EnableZoom failed");
      }
    );
  } else {
    state.zoom = false;
  }
};
// 开始对讲-结束对讲

const startTalk = async () => {
  try {
    let { data } = await talkToseppk({
      deviceId: props.vid,
      role: piniaUser.user.role,
    });
    let szTalkUrl = data.url;
    alert(szTalkUrl)
    state.myPlugin.JS_StartTalk(szTalkUrl).then(
      () => {
        console.info("JS_StartTalk success");
      },
      (err) => {
        console.info("JS_StartTalk failed", err);
      }
    );
  } catch (e) {}
};

const emitTalk = () => {
  emit("showql");
};

// 停止兑奖

const stopTalk = () => {
  state.myPlugin.JS_StopTalk().then(
    () => {
      console.info("JS_StopTalk success");
    },
    (err) => {
      console.info("JS_StopTalk failed");
    }
  );
};

watch(
  () => props.vid,
  (newval) => {
    if (newval != null && newval != "") {
      play();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
onMounted(() => {
  initPlayer();
  // play();
});

//注销时 销毁组件
onBeforeUnmount(() => {
  destoryPlayer();
});

defineExpose({
  resize,
  startTalk,
});
</script>

<style lang="scss" scoped>
.video-play {
  width: 100%;
  height: 100%;
}
</style>